package com.sino.operation.service.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sino.operation.commons.ConstantValue;
import com.sino.operation.commons.commonEnum.AspectFlag;
import com.sino.operation.commons.commonEnum.StatusInfoEnum;
import com.sino.operation.commons.commonEnum.VoucherType;
import com.sino.operation.dto.Dto;
import com.sino.operation.entity.*;
import com.sino.operation.param.inner.TaskBackPublicParam;
import com.sino.operation.param.inner.TaskCompletePublicParam;
import com.sino.operation.param.out.DepositAtNoticeParam;
import com.sino.operation.param.out.EscReciveByCounter;
import com.sino.operation.peripheral.esc.request.EscBody;
import com.sino.operation.peripheral.esc.request.NetHandle;
import com.sino.operation.util.PersistenceUtil;
import com.sino.operation.util.StringUtil;
import com.sino.operation.util.TimeUtil;
import com.sino.operation.vo.PublicInfo;
import com.sino.operation.vo.current.TaskOtherCompleteParam;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Title: Exec_710306
 * @Description: 对公定期（通知）存款、同业存放定期存款、同业存放通知存款
 * @Author dengls
 * @date 2021/10/21 10:38
 */
@Slf4j
public class Exec_710306 extends BaseAction {

    public Exec_710306(Map varMap, BizTranslist bizTranslist, SysAbMessage sysAbMessage, BizOperateLog bizOperateLog, Object registerTable, Object receiveParam) {
        super(varMap, bizTranslist, sysAbMessage, bizOperateLog, registerTable, receiveParam);
    }

    public Exec_710306(String journalNo, SysAbMessage sysAbMessage) {
        super(journalNo, sysAbMessage);
    }

    @Override
    public PersistenceUtil executeReception() throws Exception {
        log.info("对公定期（通知）存款开始");
        EscReciveByCounter receiveParam = (EscReciveByCounter) this.receiveParam;
        EscBody escBody = receiveParam.getEscBody();
        PublicInfo publicInfo = escBody.getPublicInfo();
        String json = JSONObject.toJSONString(receiveParam.getEscBody().getObject());
        DepositAtNoticeParam depositAtNoticeParam = JSONObject.parseObject(json, DepositAtNoticeParam.class);
        log.info("流程发起报文:" + depositAtNoticeParam.toString());

        String tellerPost = publicInfo.getTellerPost();
        String tellerCode = publicInfo.getTellerCode();//柜员号
        String tellerName = publicInfo.getTellerName();//柜员
        String tranDate = publicInfo.getTranDate();//发起日期
        String tranTime = publicInfo.getTranTimeStamp();//发起时间
        String orgCode = publicInfo.getOrgCode();//机构号
        String orgName = publicInfo.getOrgName();//机构名
        String imageId = publicInfo.getImageId();//影像套号
        String transCode = publicInfo.getTranCode();//交易码
        String businessType = publicInfo.getBusinessType();//业务类型
        String product_type = depositAtNoticeParam.getProduct_type();//产品类型
        String source = depositAtNoticeParam.getSource();//资金来源
        String zcpzlx = depositAtNoticeParam.getZcpzle();//转出凭证类型
        String wgzhxz = depositAtNoticeParam.getWgzhxz();//外管账户性质
        String business_no = depositAtNoticeParam.getBusiness_no();//业务编号
        String printornot = depositAtNoticeParam.getPrintornot();//是否打印证实书
        String batch_no = depositAtNoticeParam.getBatch_no();//凭证批次号
        String batch_number = depositAtNoticeParam.getBatch_number();//凭证号码
        String credentials_type = depositAtNoticeParam.getCredentials_type();//证件类型（经办人）
        String credentials_no = depositAtNoticeParam.getCredentials_no();//证件号码（经办人）
        String client_name = depositAtNoticeParam.getClient_name();//客户名称（经办人）
        String credentials_starttime = depositAtNoticeParam.getCredentials_starttime();//证件起始日期（经办人）
        String credentials_endtime = depositAtNoticeParam.getCredentials_endtime();//证件截止日期（经办人）
        String phone = depositAtNoticeParam.getPhone();//电话号码（经办人）
        String nationality = depositAtNoticeParam.getNationality();//国籍（经办人）
        String tjygh = depositAtNoticeParam.getTjygh();//推荐员工号
        String tjrxm = depositAtNoticeParam.getTjrxm();//推荐人姓名
        String bz = depositAtNoticeParam.getBz();//币种
        String account_type = depositAtNoticeParam.getAccount_type();//账户性质
        String fxfs = depositAtNoticeParam.getFxfs();//付息方式
        String zxll = depositAtNoticeParam.getZxll();//执行利率
        String yqll = depositAtNoticeParam.getYqll();//逾期利率
        String wyll = depositAtNoticeParam.getWyll();//违约利率
        String tyhth = depositAtNoticeParam.getTyhth();
        String hh = depositAtNoticeParam.getHh();
        String hm = depositAtNoticeParam.getHm();
        String journalNo = this.bizTranslist.getJournalNo();
        String cps_flag = null;
        //确定切片标志 放入流程变量 加入报文 更新登记簿表
        if (VoucherType.VOUCHERTYPE01.getValue().equals(zcpzlx) || VoucherType.VOUCHERTYPE38.getValue().equals(zcpzlx)
                || VoucherType.VOUCHERTYPE71.getValue().equals(zcpzlx)) {
            cps_flag = AspectFlag.AspectFlag1.getValue();//切片
        } else {
            cps_flag = AspectFlag.AspectFlag2.getValue();//整单
        }

        depositAtNoticeParam.setJournalNo(journalNo);
        escBody.setObject(depositAtNoticeParam);
        receiveParam.setEscBody(escBody);
        BizDespositInfo despositInfo = new BizDespositInfo();
        despositInfo.setJournalNo(journalNo);
        despositInfo.setTransCode(transCode);
        despositInfo.setImageId(imageId);
        despositInfo.setBsty(businessType);
        despositInfo.setCpsFlag(cps_flag);
        despositInfo.setProduct_type(product_type);
        despositInfo.setSource(source);
        despositInfo.setZcpzlx(zcpzlx);
        despositInfo.setWgzhxz(wgzhxz);
        despositInfo.setBusiness_no(business_no);
        despositInfo.setPrintornot(printornot);
        despositInfo.setBatch_no(batch_no);
        despositInfo.setBatch_number(batch_number);
        despositInfo.setCredentials_type(credentials_type);
        despositInfo.setCredentials_no(credentials_no);
        despositInfo.setClient_name(client_name);
        despositInfo.setCredentials_starttime(credentials_starttime);
        despositInfo.setCredentials_endtime(credentials_endtime);
        despositInfo.setPhone(phone);
        despositInfo.setNationality(nationality);
        despositInfo.setTjygh(tjygh);
        despositInfo.setTjrxm(tjrxm);
        despositInfo.setBz(bz);
        despositInfo.setFxfs(fxfs);
        if (ConstantValue.DWTZCK.equals(product_type) || ConstantValue.DWDQCK.equals(product_type)) {
            //定期存款、通知存款
        }
        if (ConstantValue.DWXYCK.equals(product_type)) {
            //单位协议存款
            despositInfo.setZxll(zxll);
            despositInfo.setYqll(yqll);
            despositInfo.setWyll(wyll);
            despositInfo.setAccount_type(account_type);
        }
        if (ConstantValue.TYCFDQ.equals(product_type) || ConstantValue.TYCFTZ.equals(product_type)) {
            //同业存放定期存款、同业存放通知存款
            despositInfo.setZxll(zxll);
            despositInfo.setYqll(yqll);
            despositInfo.setWyll(wyll);
            despositInfo.setAccount_type(account_type);
            despositInfo.setTyhth(tyhth);
            despositInfo.setHh(hh);
            despositInfo.setHm(hm);
        }
        this.bizTranslist.setSliceFlage(cps_flag);
        varMap.put("cps_flag", cps_flag);
        persistence.addEntity(despositInfo);
        return persistence;
    }

    //整单1提交方法
    public PersistenceUtil executeTotalEntry1() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal1(json);
        return persistence;
    }

    //整单2提交方法
    public PersistenceUtil executeTotalEntry2() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        this.sysAbMessage.setMessageTotal2(json);
        return persistence;
    }

    //修正岗提交方法
    public PersistenceUtil executeFixed() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        String json = JSON.toJSONString(receiveParam);
        String sliceFlage = bizTranslist.getSliceFlage();
        String journalNo = bizTranslist.getJournalNo();
        BizDespositInfo despositInfo = bizDespositInfoMapper.selectById(journalNo);
        Map<String, Map> infoInputs = receiveParam.getInfoInputs();
        despositInfo = Exec_710306_Util.CollectionHandle(infoInputs, despositInfo);//归集登记薄数据
        if (StatusInfoEnum.SLICE_FLAGE.getCode().equals(sliceFlage)) {
            this.varMap.put("cps_flag", StatusInfoEnum.SLICE_FLAGE.getCode());
        } else {
            this.varMap.put("cps_flag", StatusInfoEnum.TOTAL_FLAGE.getCode());
        }
        this.sysAbMessage.setMessageAuditing(json);
        this.sysAbMessage.setMessage(json);
        persistence.addEntity(despositInfo);
        return persistence;
    }

    //复核岗提交方法
    public PersistenceUtil executeReview() {
        return persistence;
    }

    @Override
    public PersistenceUtil executeAuth() throws Exception {
        TaskOtherCompleteParam receiveParam = (TaskOtherCompleteParam) this.receiveParam;
        TaskCompletePublicParam taskCompletePublicParam = receiveParam.getTaskCompletePublicParam();
        String completeMark = receiveParam.getTaskCompletePublicParam().getCompleteMark();
        String json = JSON.toJSONString(receiveParam);
        this.bizTranslist.setBackFlag(completeMark);//保存提交标志
        if (ConstantValue.CONDITION_PASS.equals(completeMark)) {
            BizAddImage bizAddImage = new BizAddImage();
            bizAddImage.setId(StringUtil.getId());
            bizAddImage.setJournalNo(taskCompletePublicParam.getJournalNo());
            bizAddImage.setStartTeller(taskCompletePublicParam.getCenterTellerNo());
            bizAddImage.setStartTellerName(taskCompletePublicParam.getCenterTellerName());
            bizAddImage.setStartDate(TimeUtil.getStandardTime());
            bizAddImage.setState("0");//默认未补扫
            bizAddImage.setNoPassReason(taskCompletePublicParam.getReason());
            persistence.addEntity(bizAddImage);
        }
        this.sysAbMessage.setMessageAuth(json);
        this.varMap.put("auth_flag", "0");

        return persistence;
    }


    @Override
    public PersistenceUtil executeNetwork() throws Exception {
        System.out.println("进入了网点");
        varMap.put("externel", "0");
        return this.persistence;
    }

    //回退方法
    @Override
    public PersistenceUtil executeBack() throws Exception {
        TaskBackPublicParam receiveParam = (TaskBackPublicParam) this.receiveParam;
        String backMark = receiveParam.getBackMark();
        String json = JSON.toJSONString(receiveParam);
        this.bizTranslist.setBackFlag(backMark);//保存提交标志
        this.sysAbMessage.setMessageAuth(json);
        this.varMap.put("auth_flag", backMark);
        return persistence;
    }

    @Override
    public Dto executeGetTaskList(NetHandle netHandle) {
        return new Dto();
    }

    @Override
    public PersistenceUtil executeTerminal() throws Exception {
        return persistence;
    }

    //整单获取
    @Override
    public Object executeTotalEntryTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //修正岗获取
    public Object executeFixedTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //复核岗获取
    public Object executeReviewTask() throws Exception {
        String message = sysAbMessage.getMessage();
        return JSON.parseObject(message, Map.class);
    }

    //授权岗获取
    @Override
    public Object executeAuthTask() throws Exception {
        BizDespositInfo bizDespositInfo = bizDespositInfoMapper.selectById(journalNo);
        Map<String, Map> otherFields = new HashMap<>();
        Map<String, Map> focusFields = new HashMap<>();
        Map<String, Map> authResult = new HashMap<>();
        QueryWrapper<BizDictSet> wrapper = new QueryWrapper<>();
        wrapper.eq("FIELD_TRANS_CODE", bizDespositInfo.getTransCode());
        wrapper.eq("FIELD_TRANS_TYPE", bizDespositInfo.getBsty());
        List<BizDictSet> dictSets = bizDictSetMapper.selectList(wrapper);//查询交易字段
        String messageTotal1 = sysAbMessage.getMessageTotal1();
        Map<String, Map> infoInputs = JSON.parseObject(messageTotal1, TaskOtherCompleteParam.class).getInfoInputs();
        Set<String> set = infoInputs.keySet();//中心录入字段
        String s = JSON.toJSONString(bizDespositInfo);
        Map map = JSON.parseObject(s, Map.class);
        for (BizDictSet dictSet : dictSets) {
            String fieldEg = dictSet.getFieldEg();
            String field = StringUtil.slashToFirstLetterUpper(fieldEg);//转小写
            if ("1".equals(dictSet.getFieldFocus())) {
                HashMap<String, Object> focusField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    focusField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                focusField.put("CHE", dictSet.getFieldCn());//中文名
                focusField.put("value", map.get(field));//值
                focusFields.put(fieldEg, focusField);
            } else {
                HashMap<String, Object> otherField = new HashMap<>();
                if (set.contains(fieldEg)) {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_CENTER);//中心录入
                } else {
                    otherField.put("sourceFlag", ConstantValue.SOURCE_FlAG_BRANCH);//网点录入
                }
                otherField.put("CHE", dictSet.getFieldCn());
                otherField.put("value", map.get(field));
                otherFields.put(fieldEg, otherField);
            }
        }
        authResult.put("otherFields", otherFields);
        authResult.put("focusFields", focusFields);
        return authResult;
    }

    @Override
    public PersistenceUtil executeCharge() throws Exception {
        return null;
    }
}
